<?php

namespace App\Http\Controllers\Admin;


use App\Models\Auth;
use App\Models\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class RoleController extends BaseController
{

    public function index()
    {
       $name = '';
       if (!empty($_GET['name'])){
           $name = $_GET['name'];
       }
       $data = Role::when($name,function ($query) use ($name){
            $query->where("role_name","like","%{$name}%");
       })->withTrashed()->paginate($this->pagesize);
       return view('admin.role.index',compact('data'))->with('name',$name);
    }

    public function create()
    {
        return view('admin.role.create');
    }

    public function store(Request $request)
    {
        //
        $this->validate($request,[
            'role_name' => 'required|unique:roles,role_name'
        ]);

        $role_name = $request->only('role_name');
        $sta = Role::create($role_name);
        if (!$sta) {
            return redirect(route('admin.role.create'))->withErrors(['error', '新增失败!']);
        }
        return redirect(route('admin.role.index'))->with(['success' => '新增成功!']);
    }

    public function show($id)
    {
        $data = Role::find($id);
        dd($data);
    }

    public function edit($id)
    {
        $data = Role::find($id);
        return view('admin.role.edit',compact('data'));
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'role_name' => 'required|unique:roles,role_name,' . $id . ',id'
        ]);
        $data = $request->only('role_name');
        $res = Role::find($id)->update($data);
        if (!$res) {
            return redirect(route('admin.role.edit', ['id' => $id]))->withErrors('修改失败!');
        }
        return redirect(route('admin.role.index'))->with(['success' => '修改成功!']);
    }

    public function destroy($id)
    {
        Role::find($id)->delete();
        return ['status'=>0,'msg'=>'删除成功'];
    }

    public function reset($id)
    {
        Role::onlyTrashed()->find($id)->restore();
        return redirect(route('admin.role.index'))->with('success', '恢复成功!');
    }

    public function auth(Role $role)
    {
        $auth = $role->auths->pluck('id')->toArray();
        $authAll = (new Auth())->getAllList();
        return view('admin.role.auth',compact('authAll','auth','role'));
    }

    public function authSave(Request $request, Role $role)
    {
        // 关联模型的数据同步
        $role->auths()->sync($request->get('auth'));
        return redirect(route('admin.role.auth',$role));
    }
}
